import React from 'react';
import { Modal, Form, Tree, Input, Skeleton } from 'antd';
import styles from './style.less';

const formLayout = { labelCol: { span: 7 }, wrapperCol: { span: 13 } };
const FormItem = Form.Item;

const { TreeNode } = Tree;

@Form.create()
export default class AdminActionModal extends React.PureComponent {
  static defaultProps = {
    title: '编辑',
    visible: false,
    confirmLoading: false,
    onOk: () => {},
    onCancel: () => {},
    modalAction: '',
    data: {},
    menuTree: [],
  };

  handleOk = () => {
    const { form, onOk } = this.props;
    form.validateFields((errors, values) => {
      if (errors) return;
      onOk(values);
    })
  };

  handleCheck = checkedKeys => {
    const { form } = this.props;
    form.setFieldsValue({ menuIds: checkedKeys });
  };

  renderTreeNodes = data =>
      data.map(item => {
        if (item.children) {
          return (
              <TreeNode title={item.name} key={item.id} dataRef={item}>
                {this.renderTreeNodes(item.children)}
              </TreeNode>
          );
        }
        return <TreeNode key={item.id} title={item.name} />;
      });

  getModalContent = () => {
    const { form, modalAction, data, menuTree } = this.props;
    if (modalAction === 'Add' || modalAction === 'Edit') {
      return (
        <>
          <FormItem {...formLayout} label="名称">
            {form.getFieldDecorator('name', {
              initialValue: data.name,
              rules: [
                { required: true, message: '名称不能为空' },
              ],
            })(<Input />)}
          </FormItem>
        </>
      );
    }
    if (modalAction === 'SetMenu') {
      form.getFieldDecorator('menuIds', { initialValue: data.menuIdList || [] });
      return (
        <>
          <Tree
              checkable
              onCheck={this.handleCheck}
              checkedKeys={form.getFieldValue('menuIds')}
          >
            {this.renderTreeNodes(menuTree)}
          </Tree>
        </>
      );
    }
    return <></>
  };

  render() {
    const { title, visible, confirmLoading, onCancel, loading } = this.props;
    return (
      <Modal
        title={title}
        className={styles.standardListForm}
        width={640}
        destroyOnClose
        maskClosable={false}
        visible={visible}
        confirmLoading={confirmLoading || loading}
        onOk={this.handleOk}
        onCancel={onCancel}
      >
        <Skeleton loading={loading}>
          {this.getModalContent()}
        </Skeleton>
      </Modal>
    )
  }
}
